import tkinter as tk
from tkinter import ttk
from .control_panel import ControlPanel
from .register_table import RegisterTable
from .chart_viewer import ChartViewer
from .log_viewer import LogViewer
import logging


class MainWindow(tk.Tk):
    """主窗口"""

    def __init__(self, controller, config):
        super().__init__()
        self.controller = controller
        self.config = config

        # 配置窗口
        self.title("Modbus RTU串口监控系统")
        self.geometry(config.get_gui_config().get("window_size", "1200x800"))

        # 设置主题
        self.style = ttk.Style()
        self.style.theme_use(config.get_gui_config().get("theme", "clam"))

        # 创建UI
        self.create_widgets()

        # 绑定关闭事件
        self.protocol("WM_DELETE_WINDOW", self.on_close)

    def create_widgets(self):
        """创建窗口控件"""
        # 主框架
        main_frame = ttk.Frame(self)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 左侧控制面板
        self.control_panel = ControlPanel(main_frame, self.controller, self.config)
        self.control_panel.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)

        # 右侧主显示区
        display_frame = ttk.Frame(main_frame)
        display_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 创建笔记本式选项卡
        self.notebook = ttk.Notebook(display_frame)
        self.notebook.pack(fill=tk.BOTH, expand=True)

        # 寄存器表标签页
        self.register_table = RegisterTable(self.notebook, self.controller)
        self.notebook.add(self.register_table, text="寄存器表")

        # 图表标签页
        self.chart_viewer = ChartViewer(self.notebook, self.controller)
        self.notebook.add(self.chart_viewer, text="实时图表")

        # 日志标签页
        self.log_viewer = LogViewer(self.notebook, self.controller)
        self.notebook.add(self.log_viewer, text="通信日志")

    def update_ui(self):
        """更新UI状态"""
        # 更新控制面板状态
        self.control_panel.update_status(
            self.controller.is_connected(),
            self.controller.is_polling()
        )

        # 更新寄存器表
        self.register_table.update_table()

        # 更新图表
        self.chart_viewer.update_chart()

        # 每500ms更新一次
        self.after(500, self.update_ui)

    def on_close(self):
        """关闭窗口事件处理"""
        self.controller.shutdown()
        self.destroy()